package com.kky.pp.rongyun

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.util.Pair
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.kky.pp.common.Constant
import io.rong.imkit.SpName
import com.kky.pp.entity.IMTokenGetEntity
import io.rong.imkit.event.FirebaseEventTag
import com.kky.pp.activity.home.HomeActivity
import com.kky.pp.activity.user.UserProfileInfoActivity
import com.custom.base.config.BaseConfig
import io.rong.imkit.utils.FirebaseEventUtils
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.manager.SDActivityManager
import com.custom.base.util.IntentUtil
import com.kky.pp.R
import io.rong.imkit.GlideKitImageEngine
import io.rong.imkit.IMCenter
import io.rong.imkit.RongIM
import io.rong.imkit.config.ConversationClickListener
import io.rong.imkit.config.ConversationListBehaviorListener
import io.rong.imkit.config.RongConfigCenter
import io.rong.imkit.conversation.extension.RongExtensionManager
import io.rong.imkit.conversationlist.model.BaseUiConversation
import io.rong.imlib.IRongCoreCallback
import io.rong.imlib.IRongCoreEnum
import io.rong.imlib.RongCoreClient
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import io.rong.imlib.model.UserInfo
import io.rong.sight.SightExtensionModule


object RongConfigUtil {
    fun updatePortrait() {
//        IMCenter.getInstance().setMessageInterceptor(object :MessageInterceptor{
//            override fun interceptReceivedMessage(
//                message: Message?,
//                left: Int,
//                hasPackage: Boolean,
//                offline: Boolean
//            ): Boolean {
//                return false
//            }
//
//            override fun interceptOnSendMessage(message: Message?): Boolean {
////                val expansionKey = HashMap<String?, String?>()
////                expansionKey["isPrivate"] = "true"
////                expansionKey["isRead"] = "false"
////                expansionKey["isDestroyed"] = "false"
////                message?.setExpansion(expansionKey)
////                message?.isCanIncludeExpansion = true
//                return false
//            }
//
//            override fun interceptOnSentMessage(message: Message?): Boolean {
//                return false
//            }
//
//            override fun interceptOnInsertOutgoingMessage(
//                type: Conversation.ConversationType?,
//                targetId: String?,
//                sentStatus: Message.SentStatus?,
//                content: MessageContent?,
//                sentTime: Long
//            ): Boolean {
//                return false
//            }
//
//            override fun interceptOnInsertIncomingMessage(
//                type: Conversation.ConversationType?,
//                targetId: String?,
//                senderId: String?,
//                receivedStatus: Message.ReceivedStatus?,
//                content: MessageContent?,
//                sentTime: Long
//            ): Boolean {
//                return false
//            }
//
//        })
        RongConfigCenter.featureConfig().kitImageEngine = object : GlideKitImageEngine() {
            override fun loadConversationListPortrait(context: Context, url: String, imageView: ImageView, conversation: Conversation) {
                Glide.with(context).load(url)
                    .apply(RequestOptions.bitmapTransform(CircleCrop()))
                    .into(imageView)
            }

            override fun loadConversationPortrait(context: Context, url: String, imageView: ImageView, message: Message) {
                Glide.with(context).load(url)
                    .apply(RequestOptions.bitmapTransform(CircleCrop()))
                    .into(imageView)
            }
        }
        IMCenter.setConversationClickListener(object :ConversationClickListener{
            override fun onUserTitleClick(
                context: Context?,
                conversationType: Conversation.ConversationType?,
                targetId: String?
            ): Boolean {
                if(SDActivityManager.instance.lastActivity!=null) {
                    val bundle = Bundle()
                    bundle.putBoolean("isIM", true)
                    bundle.putString("userCodeFriend", targetId)
                    IntentUtil.startActivity(UserProfileInfoActivity::class.java, bundle)
                }
                return true
            }

            override fun onUserPortraitClick(
                context: Context?,
                imageView: ImageView?,
                conversationType: Conversation.ConversationType?,
                user: UserInfo?,
                targetId: String?
            ): Boolean {
                if (user?.userId != targetId){
                    return true
                }
                if (targetId == BaseConfig.getInstance.getString(SpName.serverUserCode,"")){
                    return true
                }
                if(SDActivityManager.instance.lastActivity == null){
                    return true
                }
                FirebaseEventUtils.logEvent(FirebaseEventTag.Chat_Avatar.name)
                val bundle = Bundle()
                bundle.putBoolean("isIM",true)
                bundle.putString("userCodeFriend",targetId)
                if (imageView == null){
                    IntentUtil.startActivity(UserProfileInfoActivity::class.java,bundle)
                }else{
                    imageView.transitionName = context?.getString(R.string.home_card)
                    val pair1: Pair<View, String> =
                        Pair.create(imageView, imageView.transitionName)
                    val optionsCompat1: ActivityOptionsCompat =
                        ActivityOptionsCompat.makeSceneTransitionAnimation(context as Activity, pair1)
                    val intent = Intent(context, UserProfileInfoActivity::class.java)
                    intent.putExtra("url", user?.portraitUri)
                    intent.putExtras(bundle)
                    ActivityCompat.startActivity(context, intent, optionsCompat1.toBundle())
                }
                return true
            }

            override fun onUserPortraitLongClick(
                context: Context?,
                conversationType: Conversation.ConversationType?,
                user: UserInfo?,
                targetId: String?
            ): Boolean {

                return false
            }

            override fun onMessageClick(
                context: Context?,
                view: View?,
                message: Message?
            ): Boolean {
                return false
            }

            override fun onMessageLongClick(
                context: Context?,
                view: View?,
                message: Message?
            ): Boolean {
                return true
            }

            override fun onMessageLinkClick(
                context: Context?,
                link: String?,
                message: Message?
            ): Boolean {
                return false
            }

            override fun onReadReceiptStateClick(context: Context?, message: Message?): Boolean {
                return false
            }

        })

        RongIM.getInstance().setMessageAttachedUserInfo(true)

        RongIM.setConversationListBehaviorListener(object :ConversationListBehaviorListener{
            override fun onConversationPortraitClick(
                context: Context?,
                imageView:ImageView,
                portraitUrl:String,
                conversationType: Conversation.ConversationType?,
                targetId: String?
            ): Boolean {
                if (targetId == BaseConfig.getInstance.getString(SpName.serverUserCode,"")){
                    return true
                }

                val bundle = Bundle()
                bundle.putBoolean("isIM",true)
                bundle.putString("userCodeFriend",targetId)
//                IntentUtil.startActivity(UserProfileInfoActivity::class.java,bundle)

                val pair1: Pair<View, String> =
                    Pair.create(imageView, imageView.transitionName)
                val optionsCompat1: ActivityOptionsCompat =
                    ActivityOptionsCompat.makeSceneTransitionAnimation(context as Activity, pair1)
                val intent = Intent(context, UserProfileInfoActivity::class.java)
                intent.putExtra("url", portraitUrl)
                intent.putExtras(bundle)
                ActivityCompat.startActivity(context, intent, optionsCompat1.toBundle())
                return false
            }

            override fun onConversationPortraitLongClick(
                context: Context?,
                conversationType: Conversation.ConversationType?,
                targetId: String?
            ): Boolean {
                return false
            }

            override fun onConversationLongClick(
                context: Context?,
                view: View?,
                conversation: BaseUiConversation?
            ): Boolean {
                return true
            }

            override fun onConversationClick(
                context: Context?,
                view: View?,
                conversation: BaseUiConversation?
            ): Boolean {
                if (conversation?.mCore?.targetId.equals(BaseConfig.getInstance.getString(SpName.serverUserCode,""))) {
                    FirebaseEventUtils.logEvent(FirebaseEventTag.IM_Notification.name)
                }else {
                    FirebaseEventUtils.logEvent(FirebaseEventTag.IM_Chat.name)
                }
                return false
            }

        })

    }

    fun getUnreadConversationList():List<Conversation?>{
        var conversation = listOf<Conversation?>()
        RongCoreClient.getInstance().getUnreadConversationList(object :
            IRongCoreCallback.ResultCallback<List<Conversation?>?>() {
            override fun onSuccess(conversations: List<Conversation?>?) {
                conversation= conversations!!
                // 成功并返回会话信息
            }

            override fun onError(e: IRongCoreEnum.CoreErrorCode) {}
        }, Conversation.ConversationType.PRIVATE)
        return conversation

    }

    fun configurationRong() {
//        RongConfigCenter.conversationConfig().replaceMessageProvider(TextMessageItemProvider::class.java, MyTextMessageProvider())

        RongExtensionManager.getInstance().registerExtensionModule(SightExtensionModule())
        RongExtensionManager.getInstance().extensionConfig = MyExtensionConfig()

    }

    fun reConnectIM(token:String){
        RongIM.connect(token,  object : RongIMClient.ConnectCallback() {
            override fun onSuccess(code: String) {
            }

            override fun onError(errorCode: RongIMClient.ConnectionErrorCode) {
                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                    override fun addBody(requestBody: OkHttpBodyEntity) {
                        requestBody.setPost(Constant.im_token_Url)
                    }
                }, object : SDOkHttpResoutCallBack<IMTokenGetEntity>() {
                    override fun onSuccess(entity: IMTokenGetEntity) {
                        connectIM(entity.data.token)
                    }

                    override fun onFailure(code: Int, msg: String) {
                    }
                })
            }
            override fun onDatabaseOpened(code : RongIMClient.DatabaseOpenStatus) {
            }
        })
    }
    fun connectIM(token:String){
        RongIM.connect(token,  object : RongIMClient.ConnectCallback() {
            override fun onSuccess(code: String) {
            }

            override fun onError(errorCode: RongIMClient.ConnectionErrorCode) {
                RongIM.getInstance().logout()
                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                    override fun addBody(requestBody: OkHttpBodyEntity) {
                        requestBody.setPost(Constant.im_token_Url)
                    }
                }, object : SDOkHttpResoutCallBack<IMTokenGetEntity>() {
                    override fun onSuccess(entity: IMTokenGetEntity) {
                        connectIM(entity.data.token)
                    }

                    override fun onFailure(code: Int, msg: String) {
                        if (code == 700) {
                            UserUtil.startLogin(null)
                        }
                    }
                })
            }
            override fun onDatabaseOpened(code : RongIMClient.DatabaseOpenStatus) {
                if(RongIMClient.DatabaseOpenStatus.DATABASE_OPEN_SUCCESS == code) {
                    // 登录成功，跳转到默认会话列表页。
                    IntentUtil.startActivity(HomeActivity::class.java)
                    SDActivityManager.instance.finishAllActivityExcept(HomeActivity::class.java)
                } else {
                    //数据库打开失败，可以弹出 toast 提示。
//                    ToastUtil.toast(code.name)
                }

            }
        })
    }
    fun connectIMLogin(token:String,userCode:String,nickName:String,avatarUrl:String){
        RongIM.connect(token,  object : RongIMClient.ConnectCallback() {
            override fun onSuccess(code: String) {
            }

            override fun onError(errorCode: RongIMClient.ConnectionErrorCode) {
                RongIM.getInstance().logout()
                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                    override fun addBody(requestBody: OkHttpBodyEntity) {
                        requestBody.setPost(Constant.im_token_Url)
                    }
                }, object : SDOkHttpResoutCallBack<IMTokenGetEntity>() {
                    override fun onSuccess(entity: IMTokenGetEntity) {
                        connectIMLogin(entity.data.token,userCode,nickName,avatarUrl)

                    }

                    override fun onFailure(code: Int, msg: String) {
                        if (code == 700) {
                            UserUtil.startLogin(null)
                        }
                    }
                })
            }
            override fun onDatabaseOpened(code : RongIMClient.DatabaseOpenStatus) {
                if(RongIMClient.DatabaseOpenStatus.DATABASE_OPEN_SUCCESS == code) {
                    // 登录成功，跳转到默认会话列表页。
                    IntentUtil.startActivity(HomeActivity::class.java)
                    SDActivityManager.instance.finishAllActivityExcept(HomeActivity::class.java)
                } else {
                    //数据库打开失败，可以弹出 toast 提示。
//                    ToastUtil.toast(code.name)
                }

            }
        })
    }

}